$(document).ready(function () {

    let url = window.location.href;

    if (url.split("?").length > 1) {
        regist_Jump();
    }

    $("#seach_btn").click(function () {
        let cartgory_Id = -1;
        let serach_text = $("#search_text").val();
        let url = "/woniumall2/book.html?&bookname=" + serach_text;

        let html_obj = {
            bookname: serach_text,
            cartgoryid: cartgory_Id
        };

        console.log(html_obj);
        window.sessionStorage.setItem("html_obj", JSON.stringify(html_obj));
        window.location.href = url;
    });

    //设置cookie
    function setCookie(name, value, seconds) {
        seconds = seconds || 0;   //seconds有值就直接赋值，没有为0
        var expires = "";
        if (seconds != 0) {      //设置cookie生存时间
            var date = new Date();
            date.setTime(date.getTime() + (seconds * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=" + escape(value) + expires + "; path=/";   //转码并赋值
    }

    function setInof(key, value) {
        localStorage.setItem(key, value);
        setCookie(key, value)//存储localStorage的同时，也存储一个cookie来监听
    }

    //设置密码的事件
    $("#password_login").on("input", function () {
        //如果为空或者小于0则设置提交按钮为diabaled
        let password = $("#password_login").val();
        if (password.length < 6) {
            $("#login_btn").addClass("disabled");
            return;
        } else {
            $("#login_btn").removeClass("disabled");
        }

    })

    //设置按钮的登陆事件
    $("#login_btn").click(function () {
        if (isDisabled("#login_btn")) {
            return;
        }

        let account = $("#account").val();
        let pwd = $("#password_login").val();
        let verifycode = $("#verifycode_login").val();
        let user = {"account": account, "password": pwd};

        //发请求
        $.ajax({
            url: "/login/login",
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(user) + "" + "verifycode" + ":" + verifycode,
            success: function (responseResult) {

                if (responseResult.responseStatus == "LOGIN_SUCCESS") {
                    console.log(responseResult);
                    window.location.href = "/html/book.html"
                } else if (responseResult.responseStatus == "LOGIN_FAIL") {
                    //登陆失败
                    alert(responseResult.responseMessage);
                    img_click("#img1");
                }
            }
        });
    });


    //注册按钮
    $("#regist").click(function () {
        regist_Jump();
    });

    //跳转到注册页面
    function regist_Jump() {
        $("#nav-home-tab").removeClass("active");
        $("#nav-home-tab").removeClass("show");
        $("#nav-home-tab").attr("aria-selected", false);
        $("#nav-home").removeClass("active");
        $("#nav-home").removeClass("show");

        $("#nav-profile-tab").addClass("active");
        $("#nav-profile-tab").addClass("show");
        $("#nav-profile-tab").attr("aria-selected", true);
        $("#nav-profile").addClass("active");
        $("#nav-profile").addClass("show");
        img_click("#img2");
    }

    $("#login").click(function () {
        $("#nav-profile-tab ").removeClass("active");
        $("#nav-profile-tab ").removeClass("show");
        $("#nav-profile-tab ").attr("aria-selected", false);
        $("#nav-profile").removeClass("active");
        $("#nav-profile").removeClass("show");

        $("#nav-home-tab").addClass("active");
        $("#nav-home-tab").addClass("show");
        $("#nav-home-tab").attr("aria-selected", true);
        $("#nav-home").addClass("active");
        $("#nav-home").addClass("show");
        img_click("#img1");
    });


    //登陆表单
    $('#loginForm').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            username: {
                message: '用户名验证失败',
                validators: {
                    notEmpty: {
                        message: '用户名不能为空'
                    },
                    stringLength: {
                        min: 5,
                        max: 18,
                        message: '用户名长度必须在6到18位之间'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '用户名只能包含大写、小写、数字和下划线'
                    }
                }
            },
            password: {
                message: '密码无效',
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 20,
                        message: '密码长度必须在6到20之间'
                    },
                    different: { //不能和用户名相同
                        field: 'username',
                        message: '不能和用户名相同'
                    },
                    regexp: { //匹配规则
                        regexp: /^[a-zA-Z0-9_\.]+$/,
                        message: 'The username can only consist of alphabetical, number, dot and underscore'
                    }
                }
            }
        }
    });

    $("#registerForm").bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            username: {
                message: '用户名验证失败',
                validators: {
                    notEmpty: {
                        message: '用户名不能为空'
                    },
                    stringLength: {
                        min: 5,
                        max: 18,
                        message: '用户名长度必须在6到18位之间'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '用户名只能包含大写、小写、数字和下划线'
                    }
                }
            },
            password: {
                message: '密码无效',
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: '密码长度必须在6到30之间'
                    },
                    identical: { //相同
                        field: 'password',
                        message: '两次密码不一致'
                    },
                    different: { //不能和用户名相同
                        field: 'username',
                        message: '不能和用户名相同'
                    },
                    regexp: { //匹配规则
                        regexp: /^[a-zA-Z0-9_\.]+$/,
                        message: 'The username can only consist of alphabetical, number, dot and underscore'
                    }
                }
            },
            repassword: {
                message: '密码无效',
                validators: {

                    identical: { //相同
                        field: 'password',
                        message: '两次密码不一致'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: '邮箱不能为空'
                    },
                    emailAddress: {
                        message: '邮箱地址格式有误'
                    }

                }
            },

        }

    });

    //图片点击 传入图片名称就可以
    function img_click(id_name) {
        $(id_name).prop("src", "/code/generate?math=" + Math.random());
    }

    //图片点击事件
    $("#img1").click(function () {
        img_click("#img1");
    });

    $("#img2").click(function () {
        img_click("#img2");
    });


    //定时器
    function timer() {
        setTimeout(() => {
            $("#code_ver_span").text("");
            $("#error_div").addClass("fade");
            $("#error_div").hide(0);
        }, 2000);
    }


    //注册按钮
    $("#regist_btn").click(function () {
        if (isDisabled("#regist_btn")) {
            return;
        }
        let verifycode = $("#verifycode_regist").val();
        let username = $("#username").val();
        let password = $("#password_regist").val();
        let email = $("#email").val();
        let gender = $("input[type='radio']:checked").val();
        console.log(gender);
        $.ajax({
            type: "POST",
            url: "/login/register",
            dataType: "json",
            data: {
                account: username,
                password: password,
                email: email,
                "gender": gender,
                verifycode: verifycode
            },
            success: function (responseResult) {
                console.log(responseResult);
                //如果验证码错误
                if (responseResult.status == "VERIFYCODE_FAIL") {
                    $("#error_div").removeClass("fade");
                    $("#error_div").show(0);
                    $("#code_ver_span").text(responseResult.message);
                    timer();
                    return;
                }
                //注册成功
                if (responseResult.status == "SUCCESS") {
                    $('#login_Popup').modal('show');
                    login_timer();

                    return;
                } else {
                    $("#errorMsg").html(responseResult.message);
                    $("#error_div").removeClass("fade");
                    $("#error_div").show(0);
                    timer();
                }
            }
        });
    });

    //时时检查email是否可以用
    $("#email").on("input", function () {
        let email = $("#email").val();
        if (email.length == 0) {
            $("#email_status").text("×");
            $("#email_status").css({
                "color": "red"
            });
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
            return;
        }
        $.ajax({
            type: "POST",
            url: "/login/findEmail",
            data: {
                email: email
            },
            success: function (responseResult) {
                if (responseResult.status == "EMAIL_NO_EXISTENCE") {
                    //可用
                    $("#email_status").text("√");
                    $("#email_status").css({
                        "color": "green"
                    });
                    $("#regist_btn").removeClass("fade");
                    $("#regist_btn").show(0);
                    $("#regist_btn").removeClass("disabled");
                    return;
                } else {
                    //不可用
                    $("#email_status").text("×");
                    $("#email_status").css({
                        "color": "red"
                    });
                    $("#regist_btn").addClass("fade");
                    $("#regist_btn").hide(0);
                    $("#regist_btn").addClass("disabled");
                    return;
                }
            },
        });
    });


    //时时检查账户是否可以用
    $("#username").on("input", function () {
        let username = $("#username").val();
        if (username.length < 6) {
            //不可用
            $("#status").text("×");
            $("#status").css({
                "color": "red"
            });
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
        }
        //发请求 获取账号是否可用
        $.ajax({
            type: "POST",
            url: "/login/findAccount",
            data: {
                username: username
            },
            success: function (responseResult) {
                console.log(responseResult);
                if (responseResult.status == "SUCCESS") {
                    //可用
                    $("#status").text("√");
                    $("#regist_btn").removeClass("fade");
                    $("#regist_btn").show(0);
                    $("#regist_btn").removeClass("disabled");
                    $("#status").css({
                        "color": "green"
                    });

                } else {
                    //不可用
                    $("#status").text("×");
                    $("#status").css({
                        "color": "red"
                    });
                    $("#regist_btn").addClass("fade");
                    $("#regist_btn").hide(0);
                    $("#regist_btn").addClass("disabled");
                }
            }
        });
    })
    //密码重复和不为空
    $("#password_regist").on("input", function () {
        let password = $("#password_regist").val();
        if (password.length < 6) {
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
            return;
        }
        let repassword = $("#repassword").val();
        if (repassword != password) {
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
            return;
        }
        $("#regist_btn").removeClass("fade disabled");
        $("#regist_btn").show();
    });

    //密码重复和不为空
    $("#repassword").on("input", function () {
        let repassword = $("#repassword").val();
        if (repassword.length < 6) {
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
            return;
        }
        let password = $("#password_regist").val();
        if (repassword != password) {
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
            return;
        }
        $("#regist_btn").removeClass("fade disabled");
        $("#regist_btn").show(0);
    });

    //验证码不能为空
    $("#verifycode_regist").on("input", function () {
        let verifycode_regist = $("#verifycode_regist").val();
        if (verifycode_regist.length <= 3) {
            $("#regist_btn").addClass("fade");
            $("#regist_btn").hide(0);
            $("#regist_btn").addClass("disabled");
            return;
        }
        $("#regist_btn").removeClass("fade disabled");
        $("#regist_btn").show(0);
    })


    //注册成功去登陆
    function login_timer() {
        window.setInterval(function quit() {
            window.location.href = "../../index.html";
            $("#error_div").removeClass("fade");
            $("#error_div").show(0);
            $("#errorMsg").html(responseResult.message);
            $("#nav-profile-tab ").removeClass("active");
            $("#nav-profile-tab ").removeClass("show");
            $("#nav-profile-tab ").attr("aria-selected", false);
            $("#nav-profile").removeClass("active");
            $("#nav-profile").removeClass("show");
            $("#nav-home-tab").addClass("active");
            $("#nav-home-tab").addClass("show");
            $("#nav-home-tab").attr("aria-selected", true);
            $("#nav-home").addClass("active");
            $("#nav-home").addClass("show");
        }, 3000);
    }

    $("#now_time").click(function () {
        window.location.href = "../../index.html";
    })


    //判断属性值是不是为disabled
    function isDisabled(id_name) {

        let btn_class = $(id_name).attr("class").split(" ");

        for (let i = 0; i < btn_class.length; i++) {
            //console.log("1" + btn_class[i] + "1");
            if (btn_class[i] == 'disabled') {
                //返回true说明是disabled
                return true;
            }
        }
        //都不满足 说明没有该属性
        return false;
    }
});

